package com.yueyang.sojourn.server.service.sojourn.order;

import com.alibaba.fastjson.JSON;
import com.yueyang.sojourn.server.common.baymax.web.result.JAssert;
import com.yueyang.sojourn.server.model.enums.OrderEventTypeEnum;
import com.yueyang.sojourn.server.model.enums.OrderTypeEnum;
import com.yueyang.sojourn.server.model.po.SojournOrder;
import com.yueyang.sojourn.server.model.po.SojournOrderEvent;
import com.yueyang.sojourn.server.service.member.MemberService;
import com.yueyang.sojourn.server.service.sojourn.merch.inventory.MerchInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 订单事件监听
 *
 * @author Stephen.S
 * @since 2020/03/31
 */
@Component
@Slf4j
public class OrderEventListener {
    @Autowired
    private MemberService memberService;
    @Autowired
    private MerchInventoryService merchInventoryService;
    @Autowired
    private SojournOrderService orderService;

    @EventListener
    @Async
    public void handleOrderEvent(SojournOrderEvent event) {
        log.info("监听到订单事件,event:{}", JSON.toJSONString(event));

        try {
            // 已成交事件处理
            if (event.getType() == OrderEventTypeEnum.DEALED.getCode()) {
                SojournOrder order = this.orderService.findById(event.getOrderId());
                JAssert.pass(order != null, "订单不存在,id=" + event.getOrderId());

                //购买会员支付成功回调
                if (order != null && order.getType() == OrderTypeEnum.VIP.getCode()) {
                    memberService.paySuccessCallback(event.getOrderId());
                }
            }

            // 已成交事件处理
            if (event.getType() == OrderEventTypeEnum.CLOSED.getCode() ||
                    event.getType() == OrderEventTypeEnum.REFUNDED.getCode()) {
                SojournOrder order = this.orderService.findById(event.getOrderId());
                JAssert.pass(order != null, "订单不存在,id=" + event.getOrderId());
                if (order != null && order.getType() == OrderTypeEnum.MERCH.getCode()) {
                    // 普通商品订单被关闭或退款，则库存还原
                    merchInventoryService.giveBackInventory(0L, order.getSn(), order.getMerchId(), order.getMerchEffectDate(), order.getMerchCount());
                }
            }
            log.info("处理订单事件成功,event:{}", JSON.toJSONString(event));
        } catch (Exception e) {
            log.error("处理订单事件失败,", e.getMessage(), e);
        }
    }
}